<template>
  <div>
    <el-card style="width: 100%; height: 100%">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">物料管理</el-breadcrumb-item>
        <el-breadcrumb-item>1BOM管理</el-breadcrumb-item>
        <el-breadcrumb-item>2BOM信息管理</el-breadcrumb-item>
        <el-breadcrumb-item>3BOM信息管理列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card style="width: 100%; height: 100%; margin-top: 5px">
      <el-form :inline="true" :model="queryForm" label-width="auto">
        <el-form-item label="BOM编号/名称">
          <el-input
            v-model="queryForm.bomname"
            placeholder="请输入BOM编号/名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="产品编号/名称">
          <el-input
            v-model="queryForm.productname"
            placeholder="请输入产品编号/名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态" style="width: 250px;">
          <el-select
            style="width: 200px;"
            v-model="queryForm.bomstate"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              style="width: 200px;"
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-dropdown>
            <el-button type="info">
              更多
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleExport">导出全部</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
      <div style="margin-top: 10px">
        <el-button type="success" plain @click="handleAdd">新增+</el-button>
        <el-button type="warning" plain @click="handleImport">导入</el-button>
        <el-button type="primary" plain @click="handleExport">导出</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
      <el-table
        style="width: 100%; margin-top: 10px"
        :data="treeTableData"
        stripe
        border
        row-key="rowKey"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
        @expand-change="handleExpandChange"
        :loading="loading || detailLoading"
      >
        <el-table-column type="selection" width="55" :selectable="selectRootOnly" />
        <el-table-column prop="index" label="序号" width="70">
          <template #default="{ row }">
            <span v-if="row.level === 1">{{ row.index }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productname" label="产品名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="productcode" label="产品编号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="specification" label="规格型号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="bomcode" label="BOM编号" min-width="140" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.level === 1">{{ row.bomcode }}</span>
            <span v-else-if="row.level === 2 && row.bomcode">{{ row.bomcode }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="BOM版本" width="110">
          <template #default="{ row }">
            <span v-if="row.level === 1">{{ row.version }}</span>
            <span v-else-if="row.level === 2 && row.version">{{ row.version }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="使用量" width="110">
          <template #default="{ row }">
            <span v-if="row.level === 2 || row.level === 3">{{ row.quantity ?? '--' }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="lossrate" label="使用比例(%)" width="130">
          <template #default="{ row }">
            <span v-if="row.level === 2 || row.level === 3">{{ row.lossrate ?? 0 }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.level === 1" :type="row.bomstate ? 'success' : 'info'">
              {{ row.statusLabel }}
            </el-tag>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <template v-if="row.level === 1">
              <el-button type="primary" size="small" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" link @click="handleDelete(row)">删除</el-button>
            </template>
            <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
      <table style="margin-top: 10px; width: 100%">
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[1, 2, 3, 5]"
              background
              layout="slot,total,sizes"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </td>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="slot,prev, pager"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              prev-text="上一页"
            >
              <template #default>
                <el-button type="primary" link @click="handleCurrentChange(1)">
                  首页
                </el-button>
              </template>
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="next,slot,jumper"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              next-text="下一页"
            >
              <template #default>
                <el-button
                  type="primary"
                  link
                  @click="handleCurrentChange(pagination.pageCount || 1)"
                >
                  尾页
                </el-button>
              </template>
            </el-pagination>
          </td>
        </tr>
      </table>
    </el-card>
    
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight, ArrowDown } from "@element-plus/icons-vue";
import https from "@/Http/http";
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

// 写库 API 基础地址（也可以直接使用 https.Writes 实例）
const WRITE_API_BASE = "http://localhost:5214";

// 后端DTO接口
interface BomDTO {
  id: number;
  bomcode: string;
  bomname: string;
  productid: number;
  productcode: string;
  productname: string;
  version: string;
  bomstate: boolean;
  bomdes: string;
}

interface BomDetailDTO {
  id: number;
  bomid: number;
  materialid: number;
  materialcode: string;
  materialname: string;
  specification: string;
  unit: string;
  quantity: number;
  lossrate: number;
  sortorder: number;
  remark: string;
  nodetype: number;
  nodekey: string;
  parentnodekey: string;
}

// 前端显示用的接口
interface BomRow {
  id: number;
  bomcode: string;
  bomname: string;
  productid: number;
  productcode: string;
  productname: string;
  version: string;
  bomstate: boolean;
  bomdes?: string;
}

interface BomTableRow extends BomRow {
  index: number;
  statusLabel: string;
}

interface BomTreeRow extends BomTableRow {
  rowKey: string;
  isRoot: boolean;
  level: number;
  specification?: string;
  unit?: string;
  quantity?: number;
  lossrate?: number;
  nodetype?: number;
  nodekey?: string;
  parentnodekey?: string;
  children?: BomTreeRow[];
  hasChildren?: boolean;
  childrenLoaded?: boolean;
}

// API响应接口
interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: number;
  msg: string;
  data: T;
}

const ROOT_NODE_KEY = "ROOT";
const loading = ref(false);
const detailLoading = ref(false);
const expandingNodeLoading = ref<Set<string>>(new Set());
const tableData = ref<BomTableRow[]>([]);
const treeTableData = ref<BomTreeRow[]>([]);
const multipleSelection = ref<BomTreeRow[]>([]);

const queryForm = reactive({
  bomname: "",
  productname: "",
  bomstate: null as boolean | null,
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

// 状态选项
const statusOptions = [
  { label: "启用", value: true },
  { label: "停用", value: false },
];

const statusMap = computed(() =>
  statusOptions.reduce<Record<string, string>>((acc, cur) => {
    acc[String(cur.value)] = cur.label;
    return acc;
  }, {})
);

const router = useRouter();

// 将后端DTO转换为前端显示格式
const dtoToRow = (dto: BomDTO, index: number): BomTableRow => {
  return {
    id: dto.id,
    bomcode: dto.bomcode || "",
    bomname: dto.bomname || "",
    productid: dto.productid,
    productcode: dto.productcode || "",
    productname: dto.productname || "",
    version: dto.version || "",
    bomstate: dto.bomstate,
    bomdes: dto.bomdes || "",
    index,
    statusLabel: statusMap.value[String(dto.bomstate)] || "--",
  };
};

// 获取列表数据
const fetchTableData = async () => {
  loading.value = true;
  const params: Record<string, any> = {
    pageindex: pagination.pageIndex,
    pagesize: pagination.pageSize,
  };
  if (queryForm.bomname) params.bomname = queryForm.bomname;
  if (queryForm.productname) params.productname = queryForm.productname;
  if (queryForm.bomstate !== null) params.bomstate = queryForm.bomstate;

  try {
    const { data } = await https.Reads.get<ApiPageingResponse<BomDTO>>(`/Bom/BomGetList`, { params });
    if (data.code === 1) {
      tableData.value = (data.data || []).map((item, index) =>
        dtoToRow(item, (pagination.pageIndex - 1) * pagination.pageSize + index + 1)
      );
      pagination.totalCount = data.totalCount || 0;
      pagination.pageCount = data.pageCount || 0;
      await buildTreeData();
    } else {
      ElMessage.error(data.msg || "获取数据失败");
      tableData.value = [];
      treeTableData.value = [];
      pagination.totalCount = 0;
      pagination.pageCount = 0;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败，请稍后再试");
    tableData.value = [];
    treeTableData.value = [];
    pagination.totalCount = 0;
    pagination.pageCount = 0;
  } finally {
    loading.value = false;
  }
};

const buildTreeData = async () => {
  if (!tableData.value.length) {
    treeTableData.value = [];
    return;
  }
  detailLoading.value = true;
  try {
    const rows = await Promise.all(
      tableData.value.map(async (root) => {
        const bomDetails = await fetchBomDetailTree(root.id);
        // 将BOM明细转换为二级节点
        const children = convertDetailsToTree(bomDetails);
        // 确保每个一级节点的 rowKey 唯一
        const rootRow: BomTreeRow = {
          ...root,
          rowKey: `BOM-${root.id}`,
          isRoot: true,
          level: 1,
          specification: "",
          unit: "",
          quantity: undefined,
          lossrate: undefined,
          nodetype: 0,
          nodekey: ROOT_NODE_KEY,
          parentnodekey: "",
          children: children || [], // 二级节点（产品）
          hasChildren: (children?.length || 0) > 0,
          childrenLoaded: true,
        };
        return rootRow;
      })
    );
    treeTableData.value = rows;
  } finally {
    detailLoading.value = false;
  }
};

const fetchBomDetailTree = async (bomid: number): Promise<BomDetailDTO[]> => {
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<BomDetailDTO>>(`/Bom/BomGetDetailList`, {
      params: {
        bomid,
        pageindex: 1,
        pagesize: 1000,
      },
    });
    if (data.code === 1) {
      return data.data || [];
    }
  } catch (error) {
    console.error("获取BOM明细失败:", error);
  }
  return [];
};

const convertDetailsToTree = (details: BomDetailDTO[]): BomTreeRow[] => {
  if (!details || details.length === 0) {
    return [];
  }
  
  // 只返回二级节点（产品节点，parentnodekey为ROOT的节点）
  return details
    .filter((detail) => {
      const parentKey = (detail.parentnodekey?.trim() || ROOT_NODE_KEY).toUpperCase();
      return parentKey === ROOT_NODE_KEY || parentKey === "";
    })
    .map((detail) => {
      const nodeKey = detail.nodekey?.trim() || `NODE-${detail.id}`;
      const rowKey = `DETAIL-${detail.bomid}-${nodeKey}-${detail.id}`;
      
      return {
        id: detail.id,
        bomcode: "",
        bomname: "",
        productid: detail.materialid,
        productcode: detail.materialcode || "",
        productname: detail.materialname || "",
        version: "",
        bomstate: true,
        bomdes: "",
        index: 0,
        statusLabel: "",
        rowKey,
        isRoot: false,
        level: 2, // 二级节点（BOM产品信息）
        specification: detail.specification || "",
        unit: detail.unit || "",
        quantity: Number(detail.quantity ?? 0),
        lossrate: Number(detail.lossrate ?? 0),
        nodetype: detail.nodetype,
        nodekey: nodeKey,
        parentnodekey: ROOT_NODE_KEY,
        children: [], // 初始化为空数组，展开时动态加载
        hasChildren: true, // 标记为有子节点（需要动态加载该产品对应的BOM明细）
        childrenLoaded: false, // 标记子节点是否已加载
      } as BomTreeRow;
    });
};

// 根据产品ID查找对应的BOM
const findBomByProductId = async (productId: number): Promise<number | null> => {
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<BomDTO>>(`/Bom/BomGetList`, {
      params: {
        pageindex: 1,
        pagesize: 1000, // 获取更多数据以便查找
      },
    });
    if (data.code === 1 && data.data && data.data.length > 0) {
      // 在返回的数据中查找匹配的 productid
      const bom = data.data.find((item) => item.productid === productId);
      if (bom) {
        return bom.id;
      }
    }
  } catch (error) {
    console.error("查找产品BOM失败:", error);
  }
  return null;
};

// 处理展开事件
const handleExpandChange = async (row: BomTreeRow, expandedRows: BomTreeRow[]) => {
  // 只处理二级节点（产品节点）的展开
  if (row.level !== 2 || row.childrenLoaded) {
    return;
  }
  
  // 如果正在加载，直接返回
  if (expandingNodeLoading.value.has(row.rowKey)) {
    return;
  }
  
  expandingNodeLoading.value.add(row.rowKey);
  
  try {
    // 根据产品ID查找对应的BOM
    const bomId = await findBomByProductId(row.productid);
    
    if (bomId) {
      // 加载该BOM的明细作为三级节点
      const bomDetails = await fetchBomDetailTree(bomId);
      
      // 获取该BOM的主信息（用于三级节点中的产品显示BOM编号和版本）
      const bomInfo = await getBomInfo(bomId);
      
      // 将BOM明细转换为三级节点
      const children = convertBomDetailsToLevel3Nodes(bomDetails, row, bomInfo);
      
      // 更新节点的children
      row.children = children;
      row.childrenLoaded = true;
      
      // 如果children为空，设置hasChildren为false
      if (!children || children.length === 0) {
        row.hasChildren = false;
      }
    } else {
      // 找不到对应的BOM，设置hasChildren为false
      row.hasChildren = false;
      row.children = [];
      row.childrenLoaded = true;
    }
  } catch (error) {
    console.error("加载产品BOM明细失败:", error);
    ElMessage.error("加载产品BOM明细失败");
  } finally {
    expandingNodeLoading.value.delete(row.rowKey);
  }
};

// 获取BOM主信息
const getBomInfo = async (bomId: number): Promise<BomDTO | null> => {
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<BomDTO>>(`/Bom/BomGetList`, {
      params: {
        pageindex: 1,
        pagesize: 1000,
      },
    });
    if (data.code === 1 && data.data && data.data.length > 0) {
      const bom = data.data.find((item) => item.id === bomId);
      return bom || null;
    }
  } catch (error) {
    console.error("获取BOM信息失败:", error);
  }
  return null;
};

// 将BOM明细转换为三级节点（该产品对应的BOM明细，包括产品和物料）
const convertBomDetailsToLevel3Nodes = (details: BomDetailDTO[], parentNode: BomTreeRow, bomInfo: BomDTO | null): BomTreeRow[] => {
  if (!details || details.length === 0) {
    return [];
  }
  
  // 返回该产品BOM的所有明细作为三级节点
  return details.map((detail) => {
    const nodeKey = detail.nodekey?.trim() || `NODE-${detail.id}`;
    const rowKey = `LEVEL3-${detail.bomid}-${nodeKey}-${detail.id}`;
    
    // 如果是产品类型（nodetype=1），显示其BOM编号和版本
    let bomcode = "";
    let version = "";
    if (detail.nodetype === 1 && bomInfo) {
      // 产品类型，显示该产品BOM的编号和版本
      bomcode = bomInfo.bomcode || "";
      version = bomInfo.version || "";
    }
    
    return {
      id: detail.id,
      bomcode: bomcode,
      bomname: "",
      productid: detail.materialid,
      productcode: detail.materialcode || "",
      productname: detail.materialname || "",
      version: version,
      bomstate: true,
      bomdes: "",
      index: 0,
      statusLabel: "",
      rowKey,
      isRoot: false,
      level: 3, // 三级节点（该产品对应的BOM明细）
      specification: detail.specification || "",
      unit: detail.unit || "",
      quantity: Number(detail.quantity ?? 0),
      lossrate: Number(detail.lossrate ?? 0),
      nodetype: detail.nodetype,
      nodekey: nodeKey,
      parentnodekey: parentNode.nodekey || "",
      children: [],
      hasChildren: false, // 三级节点不再有子节点
      childrenLoaded: true,
    } as BomTreeRow;
  });
};

onMounted(() => {
  fetchTableData();
});

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  fetchTableData();
};

const handleSelectionChange = (val: BomTreeRow[]) => {
  multipleSelection.value = val.filter((item) => item.level === 1);
};

const selectRootOnly = (row: BomTreeRow) => row.level === 1;

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.bomname = "";
  queryForm.productname = "";
  queryForm.bomstate = null;
  handleQuery();
};

const handleImport = () => {
  ElMessage.info("导入功能待实现");
};

const handleExport = () => {
  ElMessage.info("导出功能待实现");
};

const handleAdd = () => {
  router.push("/BomAdd");
};

const handleEdit = (row: BomTreeRow) => {
  router.push({ path: "/BomAdd", query: { id: row.id } });
};

const handleDelete = (row: BomTreeRow) => {
  ElMessageBox.confirm("确认删除当前BOM信息吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes
        .delete<ApiResultResponse<number>>(`/Bom/BomDel`, {
          data: { id: row.id },
        })
        .then((res) => {
          const response = res.data;
          if (response.code === 1) {
            ElMessage.success(response.msg || "删除成功");
            fetchTableData();
          } else {
            ElMessage.error(response.msg || "删除失败");
          }
        })
        .catch((error) => {
          console.error("删除失败:", error);
          ElMessage.error("删除失败，请稍后再试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的BOM");
    return;
  }
  ElMessageBox.confirm(`确认批量删除所选 ${multipleSelection.value.length} 个BOM吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const deletePromises = multipleSelection.value.map((item) =>
        https.Writes.delete<ApiResultResponse<number>>(`/Bom/BomDel`, {
          data: { id: item.id },
        })
      );

      Promise.all(deletePromises)
        .then((results) => {
          const successCount = results.filter((res) => res.data.code === 1).length;
          if (successCount === multipleSelection.value.length) {
            ElMessage.success(`成功删除 ${successCount} 个BOM`);
            fetchTableData();
          } else {
            ElMessage.warning(`部分删除成功，成功 ${successCount} 个，失败 ${multipleSelection.value.length - successCount} 个`);
            fetchTableData();
          }
        })
        .catch((error) => {
          console.error("批量删除失败:", error);
          ElMessage.error("批量删除失败，请稍后再试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>

